package com.alpha;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HTMLLinkExtrator {

	private static Pattern patternTag, patternLink, patternTr;
	private static Matcher matcherTag, matcherLink, matcherTr;

	private static final String HTML_A_TAG_PATTERN = "(?i)<a([^>]+)>([.\\S\\s]*?)</a>";

	private static final String HTML_A_HREF_TAG_PATTERN = "\\s*(?i)href\\s*=\\s*(\"(index\\.cfm\\?fuseaction=Search\\.Overview&DrugName=[^\"]*)\")";
	private static final String HTML_A_HREF_TAG_PATTERN_DETAILS_LINK = "\\s*(?i)href\\s*=\\s*(\"(index\\.cfm\\?fuseaction=Search.Set_Current_Drug[^\"]*)\")";
	/*
	<a href="index.cfm?fuseaction=Search.Set_Current_Drug&amp;ApplNo=086842&amp;DrugName=DAPSONE&amp;ActiveIngred=DAPSONE&amp;SponsorApplicant=JACOBUS&amp;ProductMktStatus=1">DAPSONE<br>
		(ANDA # 086842)</a>
*/
	/**
	 * Validate html with regular expression
	 * 
	 * @param html
	 *            html content for validation
	 * @return Vector links and link text
	 */
	public static Vector<String[]> grabHTMLLinks(final String html, String searchUrl) {
		Vector<String[]> result = new Vector<String[]>();
		patternTag = Pattern.compile(HTML_A_TAG_PATTERN);
		patternLink = Pattern.compile(HTML_A_HREF_TAG_PATTERN);
		matcherTag = patternTag.matcher(html);
		while (matcherTag.find()) {
			String href = matcherTag.group(1); // href
			String linkText = matcherTag.group(2); // link text
			matcherLink = patternLink.matcher(href);
			while (matcherLink.find()) {
				String link = matcherLink.group(2); // link
				result.add(new String[] { link, linkText, searchUrl });
			}
		}
		return result;
	}
	public static Vector<String[]> grabHTMLDrugDetailsLinks(final String html) {
		Vector<String[]> result = new Vector<String[]>();
		patternTag = Pattern.compile(HTML_A_TAG_PATTERN);
		patternLink = Pattern.compile(HTML_A_HREF_TAG_PATTERN_DETAILS_LINK);
		matcherTag = patternTag.matcher(html);
		while (matcherTag.find()) {
			String href = matcherTag.group(1); // href
			String linkText = matcherTag.group(2); // link text
			matcherLink = patternLink.matcher(href);
			while (matcherLink.find()) {
				String link = matcherLink.group(2); // link
				result.add(new String[] { link, linkText });
			}
		}
		return result;
	}
	public static String grabFileData(String html, String pattern, int group) {
		String drugname = pattern;
		patternTr = Pattern.compile(drugname);
		matcherTr = patternTr.matcher(html);
		int i = 0;
		while (matcherTr.find()) {
			return matcherTr.group(group);
		}
		return "Not Found";
	}

	public static List grabDataTable(String html) {
		HashMap<String, String> data = new HashMap<String, String>();
		String anydetailsPattern = "<tr>[.\\s]+?<td [^>]* class=\"details_table\"[^>]*><strong>([^<]*)</strong></td>[.\\W\\S$]+?<strong>([.\\W\\S$]+?)</strong>[\\W\\S$]+?</tr>";
		Pattern patternTr = Pattern.compile(anydetailsPattern);
		Matcher matcherTr = patternTr.matcher(html);
		while (matcherTr.find()) {
			data.put(
					matcherTr.group(1),
					matcherTr.group(2).replaceAll("&nbsp;|<br>|</br>|\\n|\\s",
							" "));
 
		}

		List detailsList = new ArrayList();

		//String details = "<tr [^>]*>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>.*?<td[^>]*?>(.*?)</td>\\s*?</tr>";
		String details = "<tr [^>]*>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?<td[^>]*?>([.\\W\\w]*?)</td>[.\\W\\w]*?</tr>";
		//String details = "<tr [^>]*>(((((((([.\\W\\w]*?))))))))</tr>";

		Pattern patternDetails = Pattern.compile(details);
		Matcher matcherDetails = patternDetails.matcher(html);
		while (matcherDetails.find()) {
		
 			Map form = new HashMap();
			form.put("Review Classification"," "+ data.get("Review Classification"));
			form.put("FDA Application No."," "+ data.get("FDA Application No."));
			String approvalDate =" "+data.get("Original Approval or Tentative Approval Date");
			form.put("Original Approval or Tentative Approval Date",approvalDate);
			if (approvalDate.split(",").length > 1){
			form.put("Original Approval Year",approvalDate.split(",")[1]);
			}
			form.put(
					"Drug Name(s)"," "+
					matcherDetails.group(1).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " "));

			form.put("Chemical Type"," "+ data.get("Chemical Type"));
			form.put("Company"," "+ data.get("Company"));
			form.put(
					"Strength"," "+
					matcherDetails.group(3).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " "));// need to handle
																// multiple
																// ingrdents
			form.put(
					"Dosage Form/Route"," "+
					matcherDetails.group(4).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " "));// need to handle
																// multiple
																// ingrdents
			form.put(
					"MarketingStatus"," "+
					matcherDetails.group(5).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " "));// need to handle
																// multiple
																// ingrdents
			form.put(
					"RLD"," "+
					matcherDetails.group(6).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " "));// need to handle
																// multiple
																// ingrdents
			form.put(
					"TECode"," "+
					matcherDetails.group(7).replaceAll(
							"&nbsp;|<br>|</br>|\\n|\\s", " ")); 
			
			
			String ingredents = matcherDetails.group(2)	;
			form.put("Active Ingredient(s)",ingredents );
			
			ingredents = formatingredents(ingredents);
			form.put("Box",ingredents );
			
			// need to
																	// handle
																	// multiple
																	// ingrdents
			detailsList.add(form);

		}
		return detailsList;

	}

	private static String formatingredents(String ingredents) {
		ingredents = ingredents.replaceAll("&nbsp;|<br>|</br>|\\n|\\s", " ").trim();

		String [] ingredeintsList = ingredents.split("[ ]*;[ ]*");
		for (int i =0 ; i<ingredeintsList.length; i++){
			String egymapping = FDAAnalyzer.fda_egyMapping.get(ingredeintsList[i].trim());
			if (egymapping  !=null){
				ingredeintsList [i]= egymapping;
			}
		}
		FDAAnalyzer.fdaBoxesCompnents.addAll(Arrays.asList(ingredeintsList))	;	
		
		Arrays.sort(ingredeintsList );
		ingredents =(Arrays.toString(ingredeintsList));		
		String ordered = ingredents.toUpperCase().trim();
		System.out.println("|"+ordered+"|");
		return ordered;
	}

	public static void main(String args[]) {
	String ingredents = ("item1   d          ; itemz ; item3 ");
	 
	String [] ingredeintsList = ingredents.split("[ ]*;[ ]*");
	Arrays.sort(ingredeintsList );
	ingredents =(Arrays.toString(ingredeintsList));
	//Arrays.sort(ingredeintsList );
	
	 
	}
	public static void main1(String args[]) {
		String html = "";
		try {
			// Open the file that is the first
			// command line parameter
			FileInputStream fstream = new FileInputStream(
					"C:\\Users\\Ahmed\\Downloads\\html.txt");
			// Get the object of DataInputStream
			DataInputStream in = new DataInputStream(fstream);
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String strLine;
			// Read File Line By Line

			while ((strLine = br.readLine()) != null) {
				// Print the content on the console
				html = html + (strLine);
			}
			// Close the input stream
			in.close();
		} catch (Exception e) {// Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
		List datalist = HTMLLinkExtrator.grabDataTable(html);
		for (Object drugdata : datalist) {

			Iterator itr = ((Map) drugdata).keySet().iterator();
			System.out.println();
			while (itr.hasNext()) {
				String key = (String) itr.next();
				System.out.print(key + ":" + ((Map) drugdata).get(key) + "|||");

			}
		}
	}

}